#!/usr/bin/env python3
"""
将IndexTTS2作为Windows服务运行
需要安装: pip install pywin32
"""

import os
import sys
import time
import threading
import subprocess
from pathlib import Path

try:
    import win32serviceutil
    import win32service
    import win32event
    import servicemanager
except ImportError:
    print("请先安装pywin32: pip install pywin32")
    sys.exit(1)

class IndexTTSService(win32serviceutil.ServiceFramework):
    """IndexTTS2 Windows服务"""
    
    _svc_name_ = "IndexTTSService"
    _svc_display_name_ = "IndexTTS2 语音合成服务"
    _svc_description_ = "基于IndexTTS2的智能语音合成后台服务"
    
    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.is_running = True
        self.process = None
        
        # 设置工作目录
        self.work_dir = Path(__file__).parent.absolute()
        
    def SvcStop(self):
        """停止服务"""
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        self.is_running = False
        
        # 停止TTS进程
        if self.process and self.process.poll() is None:
            self.process.terminate()
            try:
                self.process.wait(timeout=10)
            except subprocess.TimeoutExpired:
                self.process.kill()
        
        win32event.SetEvent(self.hWaitStop)
        servicemanager.LogMsg(
            servicemanager.EVENTLOG_INFORMATION_TYPE,
            servicemanager.PYS_SERVICE_STOPPED,
            (self._svc_name_, '')
        )
    
    def SvcDoRun(self):
        """运行服务"""
        servicemanager.LogMsg(
            servicemanager.EVENTLOG_INFORMATION_TYPE,
            servicemanager.PYS_SERVICE_STARTED,
            (self._svc_name_, '')
        )
        
        # 启动TTS应用
        self.start_tts_application()
        
        # 等待停止信号
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
    
    def start_tts_application(self):
        """启动TTS应用"""
        try:
            # 设置环境变量
            env = os.environ.copy()
            env['GRADIO_ANALYTICS_ENABLED'] = 'False'
            
            # 构建启动命令
            python_exe = sys.executable.replace("python.exe", "pythonw.exe")
            if not Path(python_exe).exists():
                python_exe = "pythonw.exe"
            
            cmd = [
                python_exe,
                "webui.py",
                "--fp16",
                "--host", "127.0.0.1",
                "--port", "7863"
            ]
            
            # 启动进程
            self.process = subprocess.Popen(
                cmd,
                cwd=self.work_dir,
                env=env,
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
                stdin=subprocess.DEVNULL,
                creationflags=subprocess.CREATE_NO_WINDOW
            )
            
            servicemanager.LogInfoMsg(f"IndexTTS2应用已启动 PID: {self.process.pid}")
            
            # 监控进程
            def monitor_process():
                while self.is_running:
                    if self.process and self.process.poll() is not None:
                        # 进程异常退出，尝试重启
                        servicemanager.LogErrorMsg("IndexTTS2进程异常退出，正在重启...")
                        time.sleep(5)
                        if self.is_running:
                            self.start_tts_application()
                        break
                    time.sleep(10)
            
            # 启动监控线程
            monitor_thread = threading.Thread(target=monitor_process, daemon=True)
            monitor_thread.start()
            
        except Exception as e:
            servicemanager.LogErrorMsg(f"启动TTS应用失败: {e}")

def install_service():
    """安装服务"""
    try:
        win32serviceutil.InstallService(
            IndexTTSService._svc_name_,
            IndexTTSService._svc_display_name_,
            IndexTTSService._svc_description_
        )
        print("✅ IndexTTS2服务安装成功!")
        print("💡 使用以下命令管理服务:")
        print("   启动: net start IndexTTSService")
        print("   停止: net stop IndexTTSService")
        print("   或者: python windows_service.py start/stop")
    except Exception as e:
        print(f"❌ 服务安装失败: {e}")

def remove_service():
    """卸载服务"""
    try:
        win32serviceutil.RemoveService(IndexTTSService._svc_name_)
        print("✅ IndexTTS2服务卸载成功!")
    except Exception as e:
        print(f"❌ 服务卸载失败: {e}")

if __name__ == '__main__':
    if len(sys.argv) == 1:
        # 作为服务运行
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(IndexTTSService)
        servicemanager.StartServiceCtrlDispatcher()
    else:
        # 命令行管理
        command = sys.argv[1].lower()
        
        if command == 'install':
            install_service()
        elif command == 'remove':
            remove_service()
        elif command == 'start':
            win32serviceutil.StartService(IndexTTSService._svc_name_)
            print("✅ 服务启动成功!")
        elif command == 'stop':
            win32serviceutil.StopService(IndexTTSService._svc_name_)
            print("✅ 服务停止成功!")
        elif command == 'restart':
            win32serviceutil.RestartService(IndexTTSService._svc_name_)
            print("✅ 服务重启成功!")
        else:
            print("用法:")
            print("  python windows_service.py install  - 安装服务")
            print("  python windows_service.py remove   - 卸载服务")
            print("  python windows_service.py start    - 启动服务")
            print("  python windows_service.py stop     - 停止服务")
            print("  python windows_service.py restart  - 重启服务")
